import mod_item,mod_entity,mod_direction,mod_actor

class DoorOpenerSteppedOnEffect:
    def doIt(self,actor,doorOpener):
        if doorOpener.door.location:
            doorOpener.door.setLocation(None)
            
class DoorOpenerSteppedOffEffect:
    def doIt(self,actor,doorOpener): 
        door = doorOpener.door
        permLevel,permCoords = door.permLocation
        # If the door is open and there's nobody standing on its space...
        if not door.location and permCoords not in permLevel.entityMap:
            for opener in door.openers:
                # Don't open the door if anyone is standing on an opener (needs testing):
                level,coords = opener.location
                entity = level.entityMap.get(coords)
                if entity and isinstance(entity,mod_actor.Actor):
                    return
            door.setLocation(door.permLocation)

class DoorOpenerStartTurnOnEffect:
    def doIt(self,actor,doorOpener):
        if doorOpener.door.location:
            doorOpener.door.setLocation(None)

class DoorDestroyedEffect:
    def doIt(self,door,oldLocation):
        for opener in door.openers:
            opener.setLocation(None)
        del door.openers

doorOpenerPrototype = mod_item.ItemPrototype('DOOR TRIGGER',grabbable=False,visible=False)
doorOpenerPrototype.steppedOnEffect = DoorOpenerSteppedOnEffect()
doorOpenerPrototype.steppedOffEffect = DoorOpenerSteppedOffEffect()
doorOpenerPrototype.startTurnOnEffect = DoorOpenerStartTurnOnEffect()

doorPrototype = mod_entity.EntityPrototype('DOOR',maxHP=20,blocksBullets=True,blocksVision=True,structural=False)
doorPrototype.deathEffect = DoorDestroyedEffect()

# Use this function when placing a door in a level - it will put invisible "door opener"
# switches all around the door.
def placeDoor(level,coords):
    door = doorPrototype.instantiate()
    door.openers = []
    door.permLocation = (level,coords)
    door.setLocation((level,coords))
    for dir in mod_direction.ALLDIRS:
        neighbor = mod_direction.getNeighbor(coords,dir)
        doorOpener = doorOpenerPrototype.instantiate()
        doorOpener.door = door
        door.openers.append(doorOpener)
        doorOpener.setLocation((level,neighbor))
